package com.dqp.cslggroup.School;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ImageView;
import androidx.appcompat.widget.Toolbar;
import com.dd.morphingbutton.impl.LinearProgressButton;
import com.dqp.cslggroup.ConnectSever.Accept;
import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.ProgressButton.LinearProgressButtonUtil;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.UI.MyApplication;
import com.dqp.cslggroup.Util.ToastUtil;
import com.dqp.cslggroup.Util.UiUtils;
import com.dqp.cslggroup.bean.student;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

import static com.dqp.cslggroup.School.uploadImage.okHttpUploadImage;


public class Talk_submit extends BaseActivity {
    private String name, sno, content, img, gender, college;
    private ImageView add_img;
    private EditText talk_edit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.talk_add);
        EventBus.getDefault().register(this);
        Toolbar toolbar = findViewById(R.id.include_toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        initCom();

    }

    @SuppressLint("HandlerLeak")
    public void initCom() {
        LinearProgressButton talk_submit = findViewById(R.id.talk_submit);
        add_img = findViewById(R.id.add_img);
        add_img.setBackgroundResource(R.drawable.addimg);
        talk_edit = findViewById(R.id.talk_edit);
        LinearProgressButtonUtil progressButtonUtil = new LinearProgressButtonUtil(MyApplication.getContext());
        talk_submit.setOnClickListener(v ->
        {
            UiUtils.hideKeyboard(v);
            if (student()) {
                if (talk_edit.length() > 0) {
                    content = talk_edit.getText().toString();
                    if (talk_submit.getText().equals("发布")) {
                        progressButtonUtil.LPonMorphButtonClicked(talk_submit);
                        new Thread(() -> {
                            if (Accept.blacklist(sno) == 0) {
                                try {
                                    if (okHttpUploadImage(img, name, sno, content, college, gender)) {
                                        EventBus.getDefault().post(new MessageEvent("Talk_submit", 1, null));
                                    } else {
                                        EventBus.getDefault().post(new MessageEvent("Talk_submit", 2, null));
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    EventBus.getDefault().post(new MessageEvent("Talk_submit", 2, null));
                                }
                            } else {
                                EventBus.getDefault().post(new MessageEvent("Talk_submit", 3, null));
                            }
                        }).start();
                    }

                } else ToastUtil.showToast("随便说点啥吧！");
            } else ToastUtil.showToast("请先完成登录！");
        });
        add_img.setOnClickListener(v ->
        {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, 1);
        });


    }


    @SuppressLint("HandlerLeak")
    private boolean student() {
        boolean flag;
        List<student> studentList = MyApplication.getDaoInstant().getStudentDao().loadAll();
        if (studentList.size() == 0) {
            flag = false;
        } else {
            sno = studentList.get(0).getXh();
            name = studentList.get(0).getXm();
            gender = studentList.get(0).getXb();
            college = studentList.get(0).getXy();
            flag = true;
        }
        return flag;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Activity.RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            assert selectedImage != null;
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            assert cursor != null;
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            img = cursor.getString(columnIndex);
            cursor.close();
            if (img != null && img.length() > 0) {
                Bitmap bitmap = BitmapFactory.decodeFile(img);
                if (bitmap != null) {
                    add_img.setBackgroundResource(0);
                    add_img.setImageBitmap(bitmap);
                }
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void joinQQGroup(String key) {
        Intent intent = new Intent();
        intent.setData(Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D" + key));
        try {
            startActivity(intent);
        } catch (Exception e) {
            ToastUtil.showToast("请安装QQ客户端！");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("Talk_submit")) {
            if (event.getWhat() == 1) {
                talk_edit.setText("");
                ToastUtil.showToast("发布成功！");
                setResult(1, new Intent());
                finish();
            }
            if (event.getWhat() == 2) {
                ToastUtil.showToast("发布失败！");
            }
            if (event.getWhat() == 3) {
                com.dqp.cslggroup.UI.AlertDialog alertDialog = new com.dqp.cslggroup.UI.AlertDialog(Talk_submit.this);
                alertDialog.builder();
                alertDialog.setGone()
                        .setTitle("黑名单")
                        .setMsg("您曾经在软件平台发布过恶意言论，现已将您列入黑名单，您无权发布相关动态！如需解除黑名单请联系管理员！")
                        .setNegativeButton("联系", R.color.colorAccent, v -> joinQQGroup("yAjjLcdxBN2xNLvNBoCF1aB29papAvqy"))
                        .setPositiveButton("取消", R.color.colorAccent, v -> finish())
                        .show();
            }
        }
    }

}
